% Licensed under the Apache License, Version 2.0 (the "License"); you may not
% use this file except in compliance with the License. You may obtain a copy of
% the License at
%
%   http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
% License for the specific language governing permissions and limitations under
% the License.

%%% @author CA Meijer
%%% @copyright 2012 CA Meijer
%%% @doc This module provides functions for managing machine images.
%%% @end

-module(nimbula_machineimage).

%% Include files
-include("nimbula_records.hrl").
-include_lib("kernel/include/file.hrl").

%% Exported Functions
-export([add/3,
		 delete/2,
		 discover/1,
		 discover/2,
		 download/2,
		 download/3,
		 get/2,
		 list/1,
		 list/2]).

%% API Functions
add(Pid, MachineImage, File) when is_record(MachineImage, machineimage) ->
	{ok, FileInfo} = file:read_file_info(File),
	Size = FileInfo#file_info.size,
	SizesStruct = {struct, [{<<"total">>, Size}]},
	MachineImage2 = nimbula_objects:add(Pid, ?record_fields(machineimage),
										MachineImage#machineimage{sizes=SizesStruct}),
	FileUrl = erlang:binary_to_list(MachineImage2#machineimage.file),
	{ok, Body} = file:read_file(File),
	ContentRange = "bytes 0-" ++ integer_to_list(Size - 1) ++ "/" ++ integer_to_list(Size), 
	nimbula:post(Pid, FileUrl, [{"Content-Range", ContentRange}], "application/x-tar", Body).

delete(Pid, MachineImage) ->
	nimbula_objects:delete(Pid, ?record_fields(machineimage), MachineImage).

discover(Pid) ->
	nimbula_objects:discover(Pid, ?record_fields(machineimage)).

discover(Pid, Container) ->
	nimbula_objects:discover(Pid, ?record_fields(machineimage), Container).
	
download(Pid, MachineImage) ->
	{ok, BinaryData} = nimbula_objects:get(Pid, ?record_fields(machineimage), MachineImage, "application/x-tar"),
	BinaryData.

download(Pid, MachineImage, File) ->
	BinaryData = download(Pid, MachineImage),
	{ok, FilePid} = file:open(File, write),
	file:write(FilePid, BinaryData).

get(Pid, MachineImage) ->
	nimbula_objects:get(Pid, ?record_fields(machineimage), MachineImage).
	
list(Pid) ->
	nimbula_objects:list(Pid, ?record_fields(machineimage)).

list(Pid, Container) ->
	nimbula_objects:list(Pid, ?record_fields(machineimage), Container).
